package com.tongtech.common.mail.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * spring mail 工具类
 *
 * @author tong-support
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class MailService {

    private static final Logger log = LoggerFactory.getLogger(MailService.class);

    private static final Context context = new Context();
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Async
    public void sendMail(String from, String to, String subject, String templateName, Map<String, String> params) throws MessagingException, MailException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        // 设置发件人邮箱（若配置默认邮箱则不用再设置） 程序猿DD<xxx@didispace.com>
        messageHelper.setFrom("东方通客户服务<" + from + ">");
        messageHelper.setTo(to);
        messageHelper.setCc(from); //抄送账号
        messageHelper.setSubject(subject); //设置主题
        params.forEach((key, value) -> {
            context.setVariable(key, value);
        });
        String html = templateEngine.process(templateName, context);
        messageHelper.setText(html, true);
        javaMailSender.send(mimeMessage);
    }
}
